package com.dd.keel.core.common.flea;

import java.util.HashMap;
import java.util.Map;
import java.util.Collections;


public class ProtocolCodecFactory {
	
	
	private static Map<String,ProtocolEncoder> encoders = Collections.synchronizedMap(new HashMap<String,ProtocolEncoder>());
	private static Map<String,ProtocolDecoder> decoders = Collections.synchronizedMap(new HashMap<String,ProtocolDecoder>());
	
	public static String KEY_DEFAULT = "default";
	
	static{
		try {
			registerEncoder(KEY_DEFAULT,new DefaultProtocolEncoder());
			registerDecoder(KEY_DEFAULT,new DefaultProtocolDecoder());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void registerEncoder(String key,ProtocolEncoder encoder) throws Exception {
		if(!encoders.containsKey(key))
		{
			encoders.put(key, encoder);
		}
	}
	
	public static void registerDecoder(String key,ProtocolDecoder decoder) throws Exception {
		if(!decoders.containsKey(key))
		{
			decoders.put(key, decoder);
		}
	}
	
    public static ProtocolEncoder getEncoder(String key) throws Exception {
    	if(encoders.containsKey(key))
    	{
    		return encoders.get(key);
    	}
    	else
    	{
    		throw new Exception("Encoder of ["+key+"] is not found!");
    	}
    }
    
    public static ProtocolDecoder getDecoder(String key) throws Exception {
    	if(decoders.containsKey(key))
    	{
    		return decoders.get(key);
    	}
    	else
    	{
    		throw new Exception("Decoder of ["+key+"] is not found!");
    	}
    }
	
    public static ProtocolEncoder getEncoder() throws Exception {
    	if(encoders.containsKey(KEY_DEFAULT))
    	{
    		return encoders.get(KEY_DEFAULT);
    	}
    	else
    	{
    		throw new Exception("Encoder of ["+KEY_DEFAULT+"] is not found!");
    	}
    }
    
    public static ProtocolDecoder getDecoder() throws Exception {
    	if(decoders.containsKey(KEY_DEFAULT))
    	{
    		return decoders.get(KEY_DEFAULT);
    	}
    	else
    	{
    		throw new Exception("Decoder of ["+KEY_DEFAULT+"] is not found!");
    	}
    }
    
}
